# 手势检测模块：只负责检测画面中的“抬手指向”动作
import cv2
import mediapipe as mp
from config.settings import MAX_HANDS, HAND_DETECTION_CONFIDENCE, HAND_TRACKING_CONFIDENCE

# 初始化mediapipe手势检测
mp_hands = mp.solutions.hands
hands = mp_hands.Hands(
    static_image_mode=False,  # 实时视频模式
    max_num_hands=MAX_HANDS,
    min_detection_confidence=HAND_DETECTION_CONFIDENCE,
    min_tracking_confidence=HAND_TRACKING_CONFIDENCE
)
mp_drawing = mp.solutions.drawing_utils

def detect_gesture(frame):
    """
    检测画面中的手势（抬手指向）
    :param frame: 视频帧（BGR格式）
    :return: hand_detected（是否检测到手势）、frame（绘制手势骨架后的画面）
    """
    hand_detected = False
    # 转换颜色空间（mediapipe需要RGB）
    rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    results = hands.process(rgb_frame)

    # 检测到手势，绘制骨架
    if results.multi_hand_landmarks:
        hand_detected = True
        for hand_landmarks in results.multi_hand_landmarks:
            mp_drawing.draw_landmarks(
                frame, hand_landmarks, mp_hands.HAND_CONNECTIONS,
                mp_drawing.DrawingSpec(color=(0, 255, 0), thickness=2),
                mp_drawing.DrawingSpec(color=(255, 0, 0), thickness=2)
            )

    return hand_detected, frame

def release_gesture_resource():
    """释放手势检测资源（程序退出时调用）"""
    hands.close()